#pragma once
#include <string>
#include <assert.h>

namespace minidb
{
class Slice
{
public:
    Slice() :
        data_(""), size_(0) {};
    Slice(const std::string &str) :
        data_(str.c_str()), size_(str.size()) {};
    Slice(const char *data, size_t size) :
        data_(data), size_(size) {};
    Slice(const Slice &other) = default;
    Slice &operator=(const Slice &other) = default;

    const char *data() const
    {
        return data_;
    }

    const char *begin() const
    {
        return data();
    }

    const char *end() const
    {
        return data() + size();
    }

    size_t size() const
    {
        return size_;
    }

    bool empty() const
    {
        return size_ == 0;
    }

    std::string ToString() const
    {
        return std::string(data_, size_);
    }

    int compare(const Slice &b) const
    {
        // note: 字符串排序写法
        const std::size_t min_size = size_ < b.size_ ? size_ : b.size_;
        int r = memcmp(data_, b.data_, min_size);
        if (r == 0)
        {
            if (size_ < b.size_)
            {
                r = -1;
            }
            else if (size_ > b.size_)
            {
                r = 1;
            }
        }
        return r;
    }

    void Clear()
    {
        data_ = "";
        size_ = 0;
    }

    char operator[](size_t index) const
    {
        assert(index < size());
        return data_[index];
    }

    void RemovePrefix(size_t n)
    {
        assert(n < size());
        data_ += n;
        size_ -= n;
    }

private:
    const char *data_; // 指向数据的指针
    size_t size_;      // 数据的大小
};

inline bool operator==(const Slice &x, const Slice &y)
{
    return (x.size() == y.size()) && (memcmp(x.data(), y.data(), x.size()) == 0);
}

inline bool operator!=(const Slice &x, const Slice &y)
{
    return !(x == y);
}

} // namespace minidb